import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';

import { BASE_URL } from '../../config';

interface ProductDetailState {
  loading: boolean;
  error: string | null;
  data: any;
}

// 创建异步任务
export const getProductDetail = createAsyncThunk(
  'productDetail/getProductDetail', // 命名空间
  async (touristRouteId: string) => {
    const { data } = await axios.get(`${BASE_URL}/touristRoutes/${touristRouteId}`);
    return data;
  }
);
const initialState: ProductDetailState = {
  loading: true,
  error: null,
  data: null
};

export const productDetailSlice = createSlice({
  name: 'productDetail',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getProductDetail.pending, (state) => {
        state.loading = true;
      })
      .addCase(getProductDetail.fulfilled, (state, action) => {
        state.loading = false;
        state.data = action.payload;
      })
      .addCase(getProductDetail.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as any;
      });
  }
});
